<template>
    <div class="container">
        <span style="margin: 10px;">{{ room.name }}</span>
        <!-- <span style="margin: 10px;">{{ id }}</span> -->
        <!-- 顶部banner -->
        <div class="banner" v-loading="bannerLoading" style="width:50%;margin: 20px;">
            <el-carousel v-show="img && img[0].url" :interval="4000" height="400px">
                <el-carousel-item v-for="item in img" :key="item.id">
                    <!-- <h3 text="2xl" justify="center">{{ item.name }}</h3> -->
                    <!-- <el-tooltip class="box-item" effect="dark" :content="item.name" placement="bottom"> -->
                    <el-image :src="item.url" fit="contain" :preview-src-list="[item.url]">
                        <template #error>
                            <div class="image-slot">
                                <el-icon><icon-picture /></el-icon>
                            </div>
                        </template>
                    </el-image>
                    <!-- </el-tooltip> -->
                </el-carousel-item>
            </el-carousel>

        </div>
        <div v-loading="roomLoading" class="detail">
            <div>地址: {{ room.address }}</div>
            <div>类型: {{ room.category }}</div>
            <div>设施：{{ room.device }} </div>
            <div>可容住人数：{{ room.seat }} </div>
            <div>描述：{{ room.describe }} </div>
            <div>价格：<span style="font-size: 40px;">￥{{ room.price }}</span> &nbsp;/天(晚)</div>
            <div style="margin-top: 20px;">
                <el-button @click="subscribe()" type="primary" round size="large" :icon="Edit">我要预订</el-button>
            </div>
        </div>
        <!-- 底部推荐 -->
        <el-divider>
            <el-icon><star-filled /></el-icon>
        </el-divider>
        <div style="width: 100%;">
            <el-row :gutter="20">
                <el-col :span="4">
                    <div class="grid-content ep-bg-purple" />
                </el-col>
                <el-col :span="12">
                    <div class="grid-content ep-bg-purple">
                        <commentPageVue :roomId="room.id"/>
                    </div>
                </el-col>
                <el-col :span="1">
                    <div class="grid-content ep-bg-purple" >
                        <el-divider direction="vertical" style="height: 100vh;">
                            <el-icon><star-filled /></el-icon>
                        </el-divider>
                    </div>
                </el-col>
                <el-col :span="6">
                    <div class="grid-content ep-bg-purple">
                        <nameRoomPageVue :name="room.name" />
                    </div>
                </el-col>
            </el-row>
        </div>
        <!-- 预订弹窗 -->
        <div class="dialog">
            <el-dialog v-model="dialogVisible" title="预订民宿" width="30%">
                <span>请选择入住/离开日期</span><br />
                <el-date-picker v-model="dateChoose" @blur="dateBlur" :default-time="defaultTime" type="daterange"
                    range-separator="To" start-placeholder="入住日期" end-placeholder="离开日期" format="YYYY/MM/DD"
                    value-format="YYYY-MM-DD HH:mm:ss" :disabled-date="disabledDate" style="margin:10px" />
                <el-form :model="form" :rules="rules" ref="ruleFormRef" label-width="120px">
                    <!-- 从事件中获取 -->
                    <el-form-item label="民宿ID">
                        <el-input v-model="form.roomId" disabled style="width: 80%" maxlength="20"></el-input>
                    </el-form-item>
                    <el-form-item label="房间号">
                        <el-input v-model="form.roomCode" style="width: 80%" disabled></el-input>
                    </el-form-item>
                    <el-form-item label="状态">
                        <el-input v-model="form.state" style="width: 80%" disabled></el-input>
                    </el-form-item>
                    <!-- 以下需要自行填写 -->
                    <el-form-item label="入住人姓名" prop="username">
                        <el-input v-model="form.username" style="width: 80%" maxlength="16"></el-input>
                    </el-form-item>
                    <el-form-item label="入住人身份证号" prop="idCard">
                        <el-input v-model="form.idCard" style="width: 80%" maxlength="20"></el-input>
                    </el-form-item>
                    <el-form-item label="入住人手机号" prop="phone">
                        <el-input v-model="form.phone" style="width: 80%" maxlength="20"></el-input>
                    </el-form-item>
                    <el-form-item label="入住日期">
                        <el-input v-model="form.startDate" style="width: 80%" maxlength="20" disabled></el-input>
                        <!-- <el-date-picker v-model="form.startDate" type="date" placeholder="Pick a day" size="small" /> -->
                    </el-form-item>
                    <el-form-item label="离开日期">
                        <el-input v-model="form.endDate" style="width: 80%" maxlength="20" disabled></el-input>
                    </el-form-item>
                    <el-form-item label="入住天数(晚)">
                        <el-input type="number" v-model="form.days" style="width: 80%" maxlength="20"
                            disabled></el-input>
                    </el-form-item>
                    <el-form-item label="入住人数">
                        <el-input v-model="form.amount" style="width: 80%" maxlength="20"></el-input>
                    </el-form-item>
                    <el-form-item label="信息">
                        <el-input type="textarea" v-model="form.userInfo" style="width: 80%"
                            placeholder="多人入住请在此备注其余人身份信息！"></el-input>
                    </el-form-item>
                    <el-form-item label="备注">
                        <el-input type="textarea" v-model="form.userRemark" style="width: 80%"
                            placeholder="用户添加的备注"></el-input>
                    </el-form-item>
                    <el-form-item label="总价格">
                        <el-input disabled v-model="form.total" style="width: 80%"></el-input>
                    </el-form-item>
                </el-form>
                <template #footer="target">
                    <span class="dialog-footer">
                        <el-button @click="dialogVisible = false">取消</el-button>
                        <el-button type="primary" :disabled="disabledBtn" @click="checkDate()">确认</el-button>
                    </span>
                </template>

            </el-dialog>
            <!-- 支付弹窗 -->
            <el-dialog v-model="dialogVisible2" title="扫码支付" width="30%">
                <el-image src="http://localhost:8091/files/9c775d9e196e40b8968ca5ddbd5d3baa"></el-image>
                <template #footer="target">
                    <span class="dialog-footer">
                        <el-button @click="(dialogVisible2 = false)">暂不支付</el-button>
                        <el-button type="primary"
                            @click="dialogVisible2 = false, form.payState = 1, orderHandle()">支付成功</el-button>
                    </span>
                </template>
            </el-dialog>

        </div>
    </div>
</template>

<script lang="ts" setup>
import { onMounted, ref, reactive, onActivated } from '@vue/runtime-core';
import { useRoute } from 'vue-router';
import request from '@/utils/request';
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { Edit } from '@element-plus/icons-vue'
import router from '@/router'
import store from '@/store';
import nameRoomPageVue from './components/nameRoomPage.vue';
import commentPageVue from './components/commentPage.vue';
// 获取传参
const route = useRoute()
// const id = route.query?.id;
const id = route.params.id;
// console.log(route.query);
// 预订确认按钮禁用
const disabledBtn = ref(false)
// 弹窗控制和数据
const dialogVisible = ref(false)
const dialogVisible2 = ref(false)
// const form: any = ref({})
const form: any = reactive({
    username: '',
    idCard: '',
    phone: '',
    startDate: '',
    endDate: '',
    days: 1,
    amount: '',
    userInfo: '',
    userRemark: '',
    total: '',
    payState: 0,
})
onMounted(() => {
    load()
})
// onActivated(() =>{
//     load()
// })
//加载动画
const bannerLoading = ref(true)
const roomLoading = ref(true)
// 数据初始化
const img = ref([
    {
        id: '',
        url: '',

    }
])
const room = ref({
    id: '',
    name: '',
    code: '',
    device: '',
    address: '',
    category: '',
    price: '',
    seat: '',
    describe: '',
    state: '',
    endTime: '',
})
// 规则校验
const ruleFormRef = ref<FormInstance>()
const rules = reactive<FormRules>({
    username: [
        { required: true, message: '请输入您的真实姓名', trigger: 'blur' },
        { min: 2, max: 16, message: '长度在2-16个字符', trigger: 'blur' },
    ],
    phone: [
        { required: true, message: '请输入手机号', trigger: 'blur' },
        { pattern: /^(?:(?:\+|00)86)?1\d{10}$/, message: '号码格式不对', trigger: 'blur' }
    ],
    idCard: [
        { required: true, message: '请输入身份证号', trigger: 'blur' },
    ]

})
const checkRule = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            // console.log('submit!')
            // console.log(ruleForm);
            // 规则验证通过后进行注册处理
            dialogVisible.value = false
            dialogVisible2.value = true

        } else {
            console.log('error submit!', fields)
        }
    })
}
// 数据初始化
const load = () => {
    request.get('/h/room/detail', {
        params: {
            id: route.params.id ? route.params.id : 1
        }
    }).then((res: any) => {
        if (res.code === '200') {
            room.value = res.data.room
            roomLoading.value = false
            img.value = res.data.img
            bannerLoading.value = false
        } else {
            ElMessage.error('获取详情失败，即将返回主页')
            setTimeout(() => {
                router.push('/')
            }, 3000)
        }
    })
}
// 缓存中的用户信息
const user = store.getters.GET_FRONTUSER
const token = store.getters.GET_TOKEN
// 我要预订
const subscribe = () => {
    if (user == 0 || token == 0) { ElMessage.error('未登录，请先登录'); return }
    handleSubscribe()

}



// 日期选择器的处理
const defaultTime = ref<[Date, Date]>([
    // 选择日期后开始/结束日期默认的时分秒
    new Date(2000, 1, 1, 0, 0, 0),
    new Date(2000, 2, 1, 23, 59, 59),
])
const disabledDate = (time: Date) => {
    // 禁用今天以及之前的日期
    // return time.getTime() < Date.now()
    // 禁用昨天及之前的日期
    return time.getTime() < Date.now() - 24 * 60 * 60 * 1000

}
const dateChoose = ref([])
const dateBlur = (e: FocusEvent) => {
    // console.log(dateChoose.value);
    form.startDate = dateChoose.value[0]
    form.endDate = dateChoose.value[1]
    // console.log(parseInt((dateChoose.value[1] - dateChoose.value[0]) / (1000 * 60 * 60 * 24)));
    form.days = GetNumberOfDays(dateChoose.value[0], dateChoose.value[1])
    if (form.days > 0) {
        form.total = form.total * form.days
    } else {
        form.days = 1
    }
    // 判断当前房间状态，如果是预定状态这判断选择的日期是否冲突
    if (room.value.state != '空闲' && room.value.endTime > dateChoose.value[0]) {
        disabledBtn.value = true
        ElMessage.error('当前时间段已有人预订，请选择其他时间段')
    } else {
        disabledBtn.value = false
    }
}
const GetNumberOfDays = (date1: any, date2: any) => {//获得天数
    //date1：开始日期，date2结束日期
    const a1 = Date.parse(date1);
    const a2 = Date.parse(date2);
    //核心：时间戳相减，然后除以天数Math.floor((a2 - a1) / (1000 * 60 * 60 * 24))
    // return (a2 - a1) / (1000 * 60 * 60 * 24)
    return Math.floor((a2 - a1) / (1000 * 60 * 60 * 24))
};
const checkDate = () => {
    if (form.startDate == null || form.startDate == "") {
        dialogVisible2.value = false
        ElMessage.error('没有开始日期！！')
        return
    }
    if (form.endDate == null || form.endDate == "") {
        dialogVisible2.value = false
        ElMessage.error('没有结束日期！！')
        return
    }
    // dialogVisible2.value = true
    checkRule(ruleFormRef.value)
}

// 支付成功后的处理
const orderHandle = () => {
    form.state = '预订'
    request.post('/h/order', form).then((res: any) => {
        if (res.code === '0' || res.code === '200') {
            ElMessage.success('预订成功')
        } else {
            ElMessage.error('预订失败')
        }
        load()
    }).catch(err => {
        ElMessage.error('预订失败')
    })
}

// handleSubscribe 预订操作
const handleSubscribe = () => {
    form.value = {}
    //跟表中数据隔离开，深拷贝，独立对象，避免点击取消数据丢失
    // form.value = JSON.parse(JSON.stringify(row))
    form.roomId = room.value.id
    form.roomCode = room.value.code
    form.total = room.value.price
    form.state = room.value.state
    dialogVisible.value = true
}





</script>

<style  scoped>
.container {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;

}

.detail {
    width: 80vh;
    display: flex;
    flex-direction: column;
    align-items: flex-start;

}

.detail div {
    margin: 5px 0px;
}
</style>